package whr.modules.assets.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import whr.common.utils.PageUtils;
import whr.common.utils.Query;
import whr.common.validator.Assert;
import whr.modules.assets.dao.InfoDao;
import whr.modules.assets.dao.ReceiveDao;
import whr.modules.assets.entity.InfoEntity;
import whr.modules.assets.entity.ReceiveEntity;
import whr.modules.assets.entity.RepairsEntity;
import whr.modules.assets.service.InfoService;
import whr.modules.assets.service.ReceiveService;
import whr.modules.assets.service.RepairsService;


@Service("receiveService")
public class ReceiveServiceImpl extends ServiceImpl<ReceiveDao, ReceiveEntity> implements ReceiveService {

    @Autowired
    private ReceiveDao receiveDao;
    @Autowired
    private ReceiveService receiveService;
    @Autowired
    private InfoService infoService;
    @Autowired
    private InfoDao infoDao;
    @Autowired
    private RepairsService repairsService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ReceiveEntity> page = this.page(
                new Query<ReceiveEntity>().getPage(params),
                new QueryWrapper<ReceiveEntity>()
                        .like(StringUtils.isNotBlank((String) params.get("key")),"assets_num",params.get("key"))
                        .eq(StringUtils.isNotBlank((String) params.get("key2")),"create_status",params.get("key2"))
                        .orderByAsc("create_status")
        );

        return new PageUtils(page);
    }

    /**
     * 资产领用(经过资产名，领用人，),返回资产给领用表
     * @param
     *//*..reveiceReceiveEntity(receiveId=null, assetsName=电脑1, userName=manage, receiveTime=Wed Sep 11 00:00:00 CST 2024,
     createBy=, createStatus=null, createTime=null, receiveDesc=需要这个电脑) */
    @Override
    public void applySave(ReceiveEntity receive) {

        /**
         * 建立在资产状态为待用时
         * 查询出资产的状态
         */
        QueryWrapper queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("assets_num",receive.getAssetsNum());
        InfoEntity one = infoService.getOne(queryWrapper);
        if(!"0".equals(one.getAssetsStatus())){  //资产状态不是待用抛出异常
            System.out.println("资产正在使用，不能申请");
            throw new RuntimeException("资产正在使用，不能申请");
        }else{
            //拿到 领用申请理由和时间存入领用表
            String assetsName = receive.getAssetsName();  //资产名
            String userName =receive.getUserName();      // 领用申请人
            Date receiveTime =receive.getReceiveTime();   // 领用申请时间
            String receiveDesc =receive.getReceiveDesc();   // 描述
            //更新资产表/ 把状态设置成领用申请中
            infoDao.updateByAssetsNum(receive.getAssetsNum());

            //把资产的部分字段存入领用表
            ReceiveEntity apply = new ReceiveEntity();
            apply.setAssetsName(assetsName);
            apply.setAssetsNum(receive.getAssetsNum());
            apply.setUserName(userName);
            apply.setReceiveTime(receiveTime);
            apply.setReceiveDesc(receiveDesc);
            apply.setCreateStatus("0");  //审核中
            boolean save = receiveService.save(apply);
            if(save){
                return;
            }else {
                throw new RuntimeException("保存失败");
            }
        }

    }

    /**
     * 审核  前端传来 1/4  审核状态0审核中 1使用中 2维修中 3 报废 4领用失败  5 维修失败
     *      *  如果状态 不是 1，点击按钮提示，已审核，不再审核。或者提示维修中，已报废。
     * 1.判读领用表中数据库的状态（为0是领用审核）   如何审核通过设置资产使用中2    和领用表使用中1   不通过资产为待用0  领用表为领用失败4
     * 2.判读领用表中数据库的状态（为7是报修审核）  ！！重点因为前面可能操作领用归还很多次。不能用资产编号拿到想更新的那条，所有还要判断资产是否是使用中才能准确拿到数据。
     * 3.审核通过进入维修表 领用表状态为 2   资产表为 3   不过  领用表为1  资产表为 2   维修表为申请维修失败 4
     *
     */
    //从数据库中通过receiveId=41拿到,状态判断是否还要审核
    @Override
    public void updateByStatus(ReceiveEntity receive) {
        Long ReceiveId = receive.getReceiveId();
        QueryWrapper queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("receive_id",ReceiveId);
        ReceiveEntity one = receiveService.getOne(queryWrapper);

        String ReceiveStatus = one.getCreateStatus();  // 数据库中审核状态
        InfoEntity infoEntity = new InfoEntity();
        RepairsEntity repairsEntity =new RepairsEntity();
        // 根据资产编号 更新
        if("0".equals(ReceiveStatus)){   // 是领用审核
            QueryWrapper queryWrapper1 =new QueryWrapper<>();
            queryWrapper1.eq("assets_num",receive.getAssetsNum());
            if("4".equals(receive.getCreateStatus())){   // 审核领用失败
                infoEntity.setAssetsStatus("0");            //资产状态设置为待用

                String autitorDesc = receive.getAutitorChange();
                receive.setAutitorDesc(autitorDesc);
                receive.setAutitorChange("");
            }
           else if("1".equals(receive.getCreateStatus())){   //审核领取成功
                infoEntity.setAssetsAdmin(receive.getUserName());
                infoEntity.setAssetsStatus("2");  //资产状态变成使用中2
                infoEntity.setReceiveId(receive.getReceiveId());  //把领用人ID存入资产表
                //
                String autitorDesc = receive.getAutitorChange();
                receive.setAutitorDesc(autitorDesc);
                receive.setAutitorChange("");
                //
            }
            infoService.update(infoEntity,queryWrapper1);    //更新资产表
            receiveService.updateById(receive);  //  更新领用表审核信息（审核人，审核时间）加入领用表 更新审核状态
        }
        else if("3".equals(ReceiveStatus)) {  //是报修审核
            //更新维修表的状态 因为这时候领用表有多条相同数据所有还要加条件他是{报修审核}中的
            QueryWrapper queryWrapper2 =new QueryWrapper<>();
            queryWrapper2.eq("assets_num",receive.getAssetsNum());
            if("4".equals(receive.getCreateStatus())){  // 不同意报修
                infoEntity.setAssetsStatus("2");   // 2使用中
                receive.setCreateStatus("1");    // 1使用中

                String autitorDesc2 = receive.getAutitorChange();
                receive.setAutitorDesc2(autitorDesc2);
                receive.setAutitorChange("");

                QueryWrapper queryWrapper3 =new QueryWrapper<>();
                queryWrapper3.eq("assets_num",receive.getAssetsNum());
                queryWrapper3.eq("repairs_status","0");  // 0 维修申请中
                RepairsEntity one1 = repairsService.getOne(queryWrapper3);
                one1.setRepairsStatus("4");  // 4拒绝报修
                repairsService.updateById(one1);
            }
            else if("1".equals(receive.getCreateStatus())){  //同意维修
                infoEntity.setAssetsStatus("3");
                receive.setCreateStatus("2");
                //
                String autitorDesc2 = receive.getAutitorChange();
                receive.setAutitorDesc2(autitorDesc2);
                receive.setAutitorChange("");
                //
                QueryWrapper queryWrapper3 =new QueryWrapper<>();
                queryWrapper3.eq("assets_num",receive.getAssetsNum());
                queryWrapper3.eq("repairs_status","0");  // 0 维修申请中
                RepairsEntity one1 = repairsService.getOne(queryWrapper3);
                one1.setRepairsStatus("2");
                repairsService.updateById(one1);
            }
            infoService.update(infoEntity,queryWrapper2);    //更新资产表
            receiveService.updateById(receive);  //  更新领用表审核信息（审核人，审核时间）加入领用表 更新审核状态
        }
        else {
            throw  new RuntimeException("已审核，不要重复操作");
        }

    }

    /**
     * // 通过id查询角色, 人事管理可以看到所有资产领用/维修/保修列表，普通员工只能看到自己的
     * @param {t=1727149755073, page=1, limit=10, key=, userID=60}
     * @return
     */
    @Override
    public PageUtils queryByRole(Map<String, Object> params) {
        //根据id查角色
        Long userId = Long.parseLong((String) params.get("userId"));
        List<String> userRoles = receiveDao.selectUserRoles(userId);
        for (String userRole :userRoles  ) {  // 只有人事主管可以审批看到所有信息
            if(userRole.equals("人事主管")){
                PageUtils page = receiveService.queryPage(params);
                return page;
            }
        }
        //是普通员工的话
        IPage<ReceiveEntity> page = this.page(
                new Query<ReceiveEntity>().getPage(params),
                new QueryWrapper<ReceiveEntity>()
                        .eq( "user_name",params.get("userName"))
                        .like(StringUtils.isNotBlank((String) params.get("key")),"assets_num",params.get("key"))
                        .eq(StringUtils.isNotBlank((String) params.get("key2")),"create_status",params.get("key2"))
                        .orderByAsc("create_status")

        );
        return new PageUtils(page);
    }

    /**
     * 资产归还
     * @param receive{receiveId=82, assetsName=显示器, userName=user,
     *               receiveTime=Wed Sep 11 00:00:00 CST 2024, createBy=manage, assetsNum=null, createStatus=6,
     *               createTime=Wed Sep 25 00:00:00 CST 2024, receiveDesc=继续用}
     */
    @Override
    public void assetsReturn(ReceiveEntity receive) {
        //前端传回的数据
        Long receiveId =receive.getReceiveId();
        String createStatus = receive.getCreateStatus();  //6已归还
        QueryWrapper queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("receive_id",receiveId);
        ReceiveEntity one = receiveService.getOne(queryWrapper);
        one.setCreateStatus("6");
        receiveService.updateById(one);
        //更新领用表为已归还  更新资产表状态为待使用（0）
        //通过资产编号查询更新状态
        QueryWrapper queryWrapper1 =new QueryWrapper<>();
        queryWrapper1.eq("assets_num",receive.getAssetsNum());
        InfoEntity info = new InfoEntity();
        info.setAssetsStatus("0");   //资产为待用
        info.setAssetsAdmin("");   //使用人清除
        boolean update = infoService.update(info, queryWrapper1);  //false
    }


}